package com.blue.rpc.core.codec;

import java.util.List;

import com.blue.rpc.core.message.MessageJsonConvertor;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * JSON消息解码器
 * 
 * @author zhengj
 * @since 1.0 2017年3月13日
 */
public class MessageJsonDecoder extends ByteToMessageDecoder
{
	private Class<?> clazz;

	public MessageJsonDecoder(Class<?> clazz)
	{
		this.clazz = clazz;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception
	{
		if (in.readableBytes() < 4)
		{
			return;
		}
		in.markReaderIndex();
		int len = in.readInt();
		if (in.readableBytes() < len)
		{
			in.resetReaderIndex();
			return;
		}
		byte[] bytes = new byte[len];
		in.readBytes(bytes);
		Object obj = MessageJsonConvertor.toObject(bytes, clazz);
		out.add(obj);
	}

}
